package com.example.esp8266.Library.HTTP;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class TCPClient {

    private Socket socket;
    private BufferedReader reader;
    private OutputStream outputStream;

    public void connectToServer(String ipAddress) {
        new Thread(() -> {
            try {
                socket = new Socket(ipAddress, 1234); // 1234 是你要连接的端口号
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                outputStream = socket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void sendData(String data) {
        new Thread(() -> {
            try {
                outputStream.write(data.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public String receiveData() {
        try {
            return reader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void closeConnection() {
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}